package com.wn.controller;

import com.wn.entity.User;
import com.wn.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * Author 史豪通
 * Date 2024/08/26 17:05
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @RequestMapping("/login")
    @ResponseBody
    public String login(@RequestBody User user) {
        User user1 = userService.selectByName(user);
        if (user1 != null) {
            return "1"; // 登录成功
        }
        return "0"; // 登录失败
    }

    @RequestMapping("/register")
    @ResponseBody
    public String register(@RequestBody User user) {
        if (user == null || user.getName() == null || user.getPwd() == null || user.getPhone() == null) {
            return "0"; // 注册失败，参数无效
        }
        try {
            // 检查是否已存在同名用户
            User existingUser = userService.selectByName(user);
            if (existingUser != null) {
                return "0"; // 注册失败，用户已存在
            }
            // 插入新用户
            int result = userService.insertUser(user);
            return result > 0 ? "1" : "0"; // 根据插入结果返回成功或失败
        } catch (Exception e) {
            e.printStackTrace(); // 打印异常堆栈
            return "0"; // 注册失败，出现异常
        }
    }
}
